<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="评分" prop="rating">
        <el-select v-model="queryParams.rating" placeholder="请选择评分" clearable>
          <el-option v-for="item in ratingOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Back" @click="handleBack">返回</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['order:review:audit']" type="success" plain icon="Check" :disabled="multiple" @click="handleBatchApprove"
          >批量通过</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['order:review:audit']" type="warning" plain icon="Lightning" :disabled="multiple" @click="handleQuickAudit"
          >快速审核</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['order:review:audit']" type="danger" plain icon="Close" :disabled="multiple" @click="handleBatchReject"
          >批量拒绝</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['order:review:audit']" type="info" plain icon="Setting" @click="handleOpenRules">规则设置</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="商品信息" align="center" min-width="300">
        <template #default="scope">
          <div v-for="item in scope.row.orderDetail" :key="item.id" class="product-info">
            <el-image :src="item.productImage" :preview-src-list="[item.productImage]" fit="cover" class="product-image" />
            <div class="product-detail">
              <div class="product-name">{{ item.productName }}</div>
              <div v-if="item.specs" class="product-specs">
                <el-tag size="small" type="info">{{ item.specs }}</el-tag>
              </div>
              <div class="product-price">
                <span class="price">¥{{ item.price }}</span>
                <span class="quantity">x{{ item.quantity }}</span>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="评分" align="center" prop="rating" width="180">
        <template #default="scope">
          <el-rate v-model="scope.row.rating" disabled show-score text-color="#ff9900" score-template="{value}星" />
        </template>
      </el-table-column>
      <el-table-column label="评价内容" align="center" prop="content" :show-overflow-tooltip="true" min-width="200">
        <template #default="scope">
          <div class="review-content" :class="{ 'forbidden-review': forbiddenReviews.has(scope.row.id!) }">
            <div class="content-text">{{ scope.row.content }}</div>
            <div class="content-actions">
              <el-button link type="primary" @click="handleViewDetail(scope.row)">查看详情</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="评价图片" align="center" width="120">
        <template #default="scope">
          <div v-if="scope.row.images" class="review-images">
            <el-image :src="scope.row.images.split(',')[0]" :preview-src-list="scope.row.images.split(',')" fit="cover" class="review-image" />
            <span v-if="scope.row.images.split(',').length > 1" class="image-count"> +{{ scope.row.images.split(',').length - 1 }} </span>
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-hasPermi="['order:review:audit']" link type="success" icon="Check" @click="() => handleAudit(scope.row, 1)">通过</el-button>
          <el-button v-hasPermi="['order:review:audit']" link type="danger" icon="Close" @click="() => handleAudit(scope.row, 2)">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailOpen" title="评价详情" width="600px" append-to-body>
      <div class="review-detail">
        <div class="review-header">
          <div class="order-info">
            <span class="label">订单编号：</span>
            <span>{{ detailData.orderNo }}</span>
          </div>
          <div class="review-time">
            <span class="label">评价时间：</span>
            <span>{{ parseTime(detailData.createTime) }}</span>
          </div>
        </div>
        <div class="review-rating">
          <span class="label">评分：</span>
          <el-rate v-model="detailData.rating" disabled show-score text-color="#ff9900" score-template="{value}星" />
        </div>
        <div class="review-content">
          <span class="label">评价内容：</span>
          <div class="content-text">{{ detailData.content }}</div>
        </div>
        <div v-if="detailData.images" class="review-images">
          <span class="label">评价图片：</span>
          <div class="image-list">
            <el-image
              v-for="(img, index) in detailData.images.split(',')"
              :key="index"
              :src="img"
              :preview-src-list="detailData.images.split(',')"
              fit="cover"
              class="detail-image"
            />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditOpen" :title="auditTitle" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="80px">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAudit">确 定</el-button>
          <el-button @click="cancelAudit">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 违规词语检查对话框 -->
    <el-dialog v-model="forbiddenWordsDialog" title="发现违规内容" width="500px" append-to-body>
      <div class="forbidden-words-content">
        <el-alert type="warning" :closable="false" show-icon>
          <p>发现以下违规词语：</p>
          <div class="forbidden-words-list">
            <el-tag v-for="word in forbiddenWordsList" :key="word" type="danger" class="mx-1">
              {{ word }}
            </el-tag>
          </div>
          <div class="forbidden-reason mt-2">
            <p>违规原因：{{ forbiddenReason }}</p>
          </div>
        </el-alert>

        <div class="mt-4">
          <el-input v-model="editContent" type="textarea" :rows="4" placeholder="请修改评价内容" />
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelForbidden">取消</el-button>
          <el-button type="danger" @click="handleReject">直接拒绝</el-button>
          <el-button type="primary" :loading="checkingWords" @click="handleEditContent">修改后通过</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 规则设置对话框 -->
    <el-dialog v-model="rulesOpen" title="审核规则设置" width="500px" append-to-body>
      <el-form ref="rulesFormRef" :model="rulesForm" label-width="120px">
        <el-form-item label="违规直接拒绝">
          <el-switch v-model="rulesForm.autoReject" />
        </el-form-item>
        <el-form-item label="违规提示">
          <el-switch v-model="rulesForm.showWarning" />
        </el-form-item>
        <el-form-item label="快速审核阈值">
          <el-input-number v-model="rulesForm.quickAuditThreshold" :min="1" :max="100" :step="1" />
          <span class="ml-2">条/次</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitRules">确 定</el-button>
          <el-button @click="rulesOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { OrderReviewVO, OrderReviewQuery, OrderReviewForm } from '@/api/order/review/types';
import { listOrderReview, updateOrderReview } from '@/api/order/review';
import { parseTime } from '@/utils/ruoyi';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { ref, onMounted } from 'vue';
import request from '@/utils/request';

const router = useRouter();

// 评分选项
const ratingOptions = [
  { value: 1, label: '1星' },
  { value: 2, label: '2星' },
  { value: 3, label: '3星' },
  { value: 4, label: '4星' },
  { value: 5, label: '5星' }
];

const loading = ref(true);
const ids = ref<number[]>([]);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const list = ref<OrderReviewVO[]>([]);
const detailOpen = ref(false);
const detailData = ref<OrderReviewVO>({});
const auditOpen = ref(false);
const auditTitle = ref('');
const auditForm = ref({
  id: undefined,
  status: 1
});

const auditRules = ref({
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
});

const queryParams = ref<OrderReviewQuery>({
  pageNum: 1,
  pageSize: 10,
  status: 0 // 只查询待审核的评价
});

// 违规词语检查对话框
const forbiddenWordsDialog = ref(false);
const forbiddenWordsList = ref<string[]>([]);
const forbiddenReason = ref('');
const currentReview = ref<any>(null);
const editContent = ref('');
const checkingWords = ref(false);
const forbiddenReviews = ref<Set<number>>(new Set());

// 规则设置相关
const rulesOpen = ref(false);
const rulesForm = ref({
  autoReject: false, // 违规直接拒绝，默认关闭
  showWarning: true, // 违规提示
  quickAuditThreshold: 10 // 快速审核阈值
});

// 规则设置的本地存储键名
const RULES_STORAGE_KEY = 'review_rules_settings';

// 定义接口返回类型
interface ForbiddenWordsResponse {
  words: string[];
  reason: string;
}

interface ForbiddenCategoriesResponse {
  [key: string]: string;
}

/** 查询订单评价列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listOrderReview(queryParams.value);
    list.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    status: 0
  };
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderReviewVO[]) => {
  ids.value = selection.map((item) => item.id!);
  multiple.value = !selection.length;
};

/** 查看详情按钮操作 */
const handleViewDetail = (row: OrderReviewVO) => {
  detailData.value = row;
  detailOpen.value = true;
};

/** 审核按钮操作 */
const handleAudit = async (row: OrderReviewVO, result: number) => {
  currentReview.value = row; // 保存当前评论
  if (result === 1) {
    // 通过审核
    // 如果已经标记为违规，直接显示修改对话框
    if (forbiddenReviews.value.has(row.id!)) {
      editContent.value = row.content;
      forbiddenWordsDialog.value = true;
      return;
    }
  }
  // 直接审核
  await submitForbiddenAudit(row, result);
};

/** 批量通过 */
const handleBatchApprove = async () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要审核的评价');
    return;
  }
  try {
    // 如果没有违规内容，执行批量通过
    for (const id of ids.value) {
      await updateOrderReview({
        id: id,
        status: 1
      } as OrderReviewForm);
    }

    ElMessage.success('批量通过成功');
    getList();
  } catch (error) {
    console.error('批量通过失败:', error);
    ElMessage.error('批量通过失败');
  }
};

/** 批量拒绝 */
const handleBatchReject = async () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要审核的评价');
    return;
  }

  // 添加确认对话框
  try {
    await ElMessageBox.confirm(`确认要拒绝选中的 ${ids.value.length} 条评价吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
  } catch {
    return;
  }

  try {
    // 直接执行批量拒绝，不再检查违规词
    for (const id of ids.value) {
      await updateOrderReview({
        id: id,
        status: 2
      } as OrderReviewForm);
    }

    ElMessage.success('批量拒绝成功');
    getList();
  } catch (error) {
    console.error('批量拒绝失败:', error);
    ElMessage.error('批量拒绝失败');
  }
};

/** 取消审核 */
const cancelAudit = () => {
  auditOpen.value = false;
  auditForm.value = {
    id: undefined,
    status: 1
  };
};

/** 提交审核 */
const submitAudit = async () => {
  try {
    const data = {
      id: currentReview.value.id, // 使用当前评论的ID
      status: auditForm.value.status
    };
    await updateOrderReview(data as OrderReviewForm);
    ElMessage.success('审核成功');
    auditOpen.value = false;
    forbiddenWordsDialog.value = false;
    getList();
  } catch (error) {
    console.error('审核失败:', error);
    ElMessage.error('审核失败');
  }
};

/** 提交违规内容审核 */
const submitForbiddenAudit = async (row: OrderReviewVO, result: number, content?: string) => {
  try {
    const data = {
      id: row.id,
      status: result,
      content: content || row.content
    };
    await updateOrderReview(data as OrderReviewForm);
    ElMessage.success('审核成功');
    auditOpen.value = false;
    forbiddenWordsDialog.value = false;
    getList();
  } catch (error) {
    console.error('审核失败:', error);
    ElMessage.error('审核失败');
  }
};

/** 快速审核 */
const handleQuickAudit = async () => {
  if (ids.value.length === 0) {
    ElMessage.warning('请选择要审核的评价');
    return;
  }

  if (ids.value.length > rulesForm.value.quickAuditThreshold) {
    ElMessage.warning(`快速审核一次最多处理${rulesForm.value.quickAuditThreshold}条评价`);
    return;
  }

  try {
    const selectedRows = list.value.filter((r) => ids.value.includes(r.id!));
    const approvedIds: number[] = [];
    const rejectedIds: number[] = [];

    for (const row of selectedRows) {
      // 如果已经标记为违规，直接显示修改对话框
      if (forbiddenReviews.value.has(row.id!)) {
        currentReview.value = row;
        editContent.value = row.content;
        forbiddenWordsDialog.value = true;
        return;
      }

      try {
        const { words } = await checkForbiddenWords(row.content);
        if (words.length > 0) {
          // 如果设置了违规直接拒绝
          if (rulesForm.value.autoReject) {
            rejectedIds.push(row.id!);
          } else {
            // 否则显示修改对话框
            currentReview.value = row;
            forbiddenWordsList.value = words;
            forbiddenReason.value = '包含违规内容';
            editContent.value = row.content;
            forbiddenWordsDialog.value = true;
            // 添加红色标记
            forbiddenReviews.value.add(row.id!);
            return;
          }
        } else {
          approvedIds.push(row.id!);
        }
      } catch (error) {
        console.error('违规词检测失败:', error);
        ElMessage.error('违规词检测失败，请稍后重试');
        return;
      }
    }

    // 批量处理通过的评价
    if (approvedIds.length > 0) {
      for (const id of approvedIds) {
        await updateOrderReview({
          id: id,
          status: 1
        } as OrderReviewForm);
      }
    }

    // 批量处理拒绝的评价
    if (rejectedIds.length > 0) {
      for (const id of rejectedIds) {
        await updateOrderReview({
          id: id,
          status: 2
        } as OrderReviewForm);
      }
    }

    ElMessage.success(`快速审核完成：通过${approvedIds.length}条，拒绝${rejectedIds.length}条`);
    getList();
  } catch (error) {
    console.error('快速审核失败:', error);
    ElMessage.error('快速审核失败');
  }
};

/** 修改内容 */
const handleEditContent = async () => {
  try {
    checkingWords.value = true;
    // 检查修改后的内容
    const { words, reason } = await checkForbiddenWords(editContent.value);
    if (words.length > 0) {
      // 如果修改后仍然包含违规词，更新显示
      forbiddenWordsList.value = words;
      forbiddenReason.value = reason;
      ElMessage.warning('修改后的内容仍然包含违规词，请继续修改');
      return;
    }

    // 如果修改后没有违规词，提交审核
    await submitForbiddenAudit(currentReview.value, 1, editContent.value);
    // 移除违规标记
    forbiddenReviews.value.delete(currentReview.value.id!);
    // 关闭对话框
    forbiddenWordsDialog.value = false;
  } catch (error) {
    console.error('违规词检测失败:', error);
    ElMessage.error('违规词检测失败，请稍后重试');
  } finally {
    checkingWords.value = false;
  }
};

/** 直接拒绝 */
const handleReject = () => {
  // 移除违规标记
  forbiddenReviews.value.delete(currentReview.value.id!);
  submitForbiddenAudit(currentReview.value, 2);
  // 关闭对话框
  forbiddenWordsDialog.value = false;
};

/** 修改违规词对话框的取消按钮处理 */
const handleCancelForbidden = () => {
  forbiddenWordsDialog.value = false;
  // 保持违规标记，但不关闭对话框
};

/** 返回按钮操作 */
const handleBack = () => {
  router.push('/order/review');
};

/** 打开规则设置 */
const handleOpenRules = () => {
  // 从本地存储加载规则设置
  const savedRules = localStorage.getItem(RULES_STORAGE_KEY);
  if (savedRules) {
    try {
      const parsedRules = JSON.parse(savedRules);
      rulesForm.value = {
        ...rulesForm.value,
        ...parsedRules
      };
    } catch (error) {
      console.error('加载规则设置失败:', error);
    }
  }
  rulesOpen.value = true;
};

/** 提交规则设置 */
const submitRules = () => {
  try {
    // 保存规则设置到本地存储
    localStorage.setItem(RULES_STORAGE_KEY, JSON.stringify(rulesForm.value));
    rulesOpen.value = false;
    ElMessage.success('规则设置已保存');
  } catch (error) {
    console.error('保存规则设置失败:', error);
    ElMessage.error('保存规则设置失败');
  }
};

// 检查文本是否包含违规词语
const checkForbiddenWords = async (text: string): Promise<{ words: string[]; reason: string }> => {
  try {
    const response = await request({
      url: '/ai/api/ai/check-forbidden-words',
      method: 'post',
      data: { text }
    });
    console.log(response);

    // 直接使用返回的数据，不再检查code
    const data = response.data || response;
    if (data && data.words) {
      return {
        words: data.words,
        reason: data.reason || ''
      };
    }
    return { words: [], reason: '' };
  } catch (error) {
    console.error('违规词检测失败:', error);
    ElMessage.error('违规词检测失败，请稍后重试');
    return { words: [], reason: '' };
  }
};

// 获取违规词语分类
const getForbiddenWordCategories = async () => {
  try {
    const response = await request({
      url: '/ai/api/ai/forbidden-word-categories',
      method: 'get'
    });

    // 直接返回数据，不再检查code
    return response.data || response || {};
  } catch (error) {
    console.error('获取违规词分类失败:', error);
    return {};
  }
};

onMounted(() => {
  getList();
  // 从本地存储加载规则设置
  const savedRules = localStorage.getItem(RULES_STORAGE_KEY);
  if (savedRules) {
    try {
      const parsedRules = JSON.parse(savedRules);
      rulesForm.value = {
        ...rulesForm.value,
        ...parsedRules
      };
    } catch (error) {
      console.error('加载规则设置失败:', error);
    }
  }
});
</script>

<style scoped>
.product-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 12px;
  border-radius: 8px;
  background-color: #f5f7fa;
  transition: all 0.3s;
}

.product-info:hover {
  background-color: #ecf5ff;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 16px;
  border-radius: 6px;
  object-fit: cover;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-detail {
  flex: 1;
  text-align: left;
}

.product-name {
  font-size: 15px;
  color: #303133;
  margin-bottom: 8px;
  font-weight: 500;
}

.product-specs {
  margin-bottom: 8px;
}

.product-price {
  font-size: 14px;
  color: #606266;
}

.product-price .price {
  color: #f56c6c;
  font-weight: 500;
  margin-right: 12px;
}

.product-price .quantity {
  color: #909399;
}

.review-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px;
}

.content-text {
  text-align: left;
  line-height: 1.5;
  word-break: break-all;
}

.content-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 4px;
}

.forbidden-review {
  color: #f56c6c;
  background-color: #fef0f0;
  border-radius: 4px;
}

.forbidden-review .content-text {
  color: #f56c6c;
}

.forbidden-review .content-actions {
  border-top: 1px dashed #fde2e2;
  padding-top: 8px;
  margin-top: 8px;
}

.review-images {
  position: relative;
  display: inline-block;
}

.review-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

.image-count {
  position: absolute;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 2px 6px;
  border-radius: 0 0 4px 0;
  font-size: 12px;
}

.review-detail {
  padding: 20px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.review-rating {
  margin-bottom: 20px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.detail-image {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  object-fit: cover;
}

.label {
  color: #606266;
  font-weight: 500;
  margin-right: 8px;
}

.forbidden-words-content {
  .forbidden-words-list {
    margin-top: 10px;
    .el-tag {
      margin: 5px;
    }
  }
}
</style>
